package com.beiding.isolateloader;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

//通常一个隔离环境一个ClassFinder
public class ClassFinder {

    //指定一个类加载器,该类加载器并不会真实加载某个类,而是用来寻找Class资源
    private ClassLoader classClassLoader;

    private Map<String, byte[]> dataMap = new HashMap<>();

    private Set<String> passNames = new HashSet<>();

    public ClassFinder(ClassLoader classClassLoader) {
        this.classClassLoader = classClassLoader;
    }

    //将找到的资源返回为 byte 数据
    public byte[] getClassData(String className) {

        if (passNames.contains(className)) {
            return null;
        }

        byte[] bytes = dataMap.get(className);

        if (bytes != null) {
            return bytes;
        }

        InputStream resourceAsStream = classClassLoader.getResourceAsStream(className.replace(".", "/") + ".class");

        if (resourceAsStream == null) {
            passNames.add(className);
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        try {
            while ((len = resourceAsStream.read(buff)) != -1) {
                byteArrayOutputStream.write(buff, 0, len);
            }

        } catch (Exception ignore) {

        } finally {
            try {
                resourceAsStream.close();
            } catch (Exception ignore) {
            }
        }
        bytes = byteArrayOutputStream.toByteArray();
        dataMap.put(className, bytes);
        return bytes;
    }

}
